package com.ly.mp.busicen.rule.field.validator.plugin;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.ly.mp.busicen.rule.field.validator.IValidData;
import com.ly.mp.busicen.rule.field.validator.IValidation;
import com.ly.mp.busicen.rule.field.validator.ValidatorBase;

@Component
public class FieldDateOrderValid extends ValidatorBase {

	private static final String FORMATER = "yyyy-MM-dd HH:mm:ss";
	private static final String FORMATER_T = "yyyy-MM-dd['T'HH:mm:ss[Z]]";
	private static final String FORMATER_S = "yyyy-MM-dd";

	@Override
	public boolean valid(IValidData validData, IValidation validation) {
		String param = validation.strParam();
		if (!StringUtils.isEmpty(param)) {
			String[] mm = validation.strParam().split(",");
			if (mm.length > 1) {
				LocalDateTime[] values = new LocalDateTime[mm.length];
				if (convertValues(validData, mm, values)) {
					for (int i = 0; i < values.length - 1; i++) {
						if (values[i].isAfter(values[i + 1])) {
							return false;
						}
					}
				}
			}
		}
		return true;
	}

	Boolean convertValues(IValidData validData, String[] keys, LocalDateTime[] values) {
		Map<String, ?> data = validData.source();
		for (int i = 0; i < keys.length; i++) {
			Object value = data.get(keys[i]);
			if("__now".equalsIgnoreCase(keys[i])) {
				values[i] =  LocalDate.now().atTime(23, 59, 59);
				continue;
			}
			if (value == null) {
				return false;
			}
			if (value instanceof LocalDateTime) {
				values[i] = (LocalDateTime) value;
				continue;
			}
			if (value instanceof String) {
				if (StringUtils.isEmpty(value)) {
					return false;
				}
				LocalDateTime temp = null;
				if (value.toString().contains("T")) {
					temp = LocalDateTime.parse(value.toString(), DateTimeFormatter.ofPattern(FORMATER_T));
				}else if(FORMATER_S.length() == value.toString().length()) {
					temp = LocalDateTime.parse(value.toString()+" 00:00:00", DateTimeFormatter.ofPattern(FORMATER_S+" HH:mm:ss"));
				}else {
					temp = LocalDateTime.parse(value.toString(), DateTimeFormatter.ofPattern(FORMATER));
				}
				values[i] = temp;
				continue;
			}
			if (value instanceof Timestamp) {
				values[i] = ((Timestamp) value).toLocalDateTime();
				continue;
			}
		}

		return true;
	}

	@Override
	public String validName() {
		return "dateorder";
	}

}
